package com.lu.dao.ds2;


import com.lu.model.Message;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Repository("messageDao2")
public class MessageDao {


    @Resource(name = "sessionFactory2")
    private SessionFactory sessionFactory;


    @Resource(name = "jdbcTemplate2")
    private JdbcTemplate jdbcTemplate;

    public void save(Message message) {
        Session session = sessionFactory.getCurrentSession();
        session.save(message);
        //session.flush();
    }

    public Message get(Long id) {
        Session session = sessionFactory.getCurrentSession();
        Message message = session.get(Message.class, id);
        return message;
    }

    public Message get2(Long id) {

        StringBuffer sb = new StringBuffer();
        sb.append(" select * from Message where content= ? ");
        List<Long> args = new ArrayList<Long>();
        args.add(id);
        List<Message> messages = jdbcTemplate.query(sb.toString(), args.toArray(), BeanPropertyRowMapper.newInstance(Message.class));
        if (CollectionUtils.isEmpty(messages)) {
            return null;
        }
        return messages.get(0);
    }
}
